<template>
    <page-box>
        <template v-slot:header>
            <ask-breadcrumb>
                <template v-for="(item, index) in $getBreadCrumbsName($route.path)">
                    <ask-breadcrumb-item :key="index" v-if="item.path" :to="'/' + item.path">{{ item.meta.title }}</ask-breadcrumb-item>
                    <ask-breadcrumb-item :key="index" v-else>{{ item.meta.title }}</ask-breadcrumb-item>
                </template>
                <ask-breadcrumb-item name="VillageDeclareFillIn"></ask-breadcrumb-item>
            </ask-breadcrumb>
        </template>
        <page-search>
            <page-search-column class="fixed-column">
                <page-search-item class="left">
                    <div class="title">
                        <div class="name">{{ $route.query.name }}</div>
                        <el-tooltip
                            v-if="Number(descriptionType) === 1"
                            effect="dark"
                            :content="$route.query.description"
                            :disabled="!$route.query.description"
                            placement="top">
                            <p class="description">
                                {{ $route.query.description || "暂无描述" }}
                            </p>
                        </el-tooltip>
                        <p class="btn" v-if="Number(descriptionType) === 2" @click="showRichText">查看表单介绍</p>
                    </div>
                </page-search-item>
                <page-search-item class="right">
                    <el-button @click="save()" type="primary" size="mini">保存</el-button>
                    <el-button v-if="!isEdit" type="primary" @click="save('toNext')" size="mini">保存并下一条</el-button>
                    <el-button @click="goBack" size="mini">取消</el-button>
                </page-search-item>
            </page-search-column>
        </page-search>
        <preview-template
            ref="previewTemplate"
            :key="key"
            v-if="show"
        ></preview-template>
        <el-dialog
            title="表单介绍详情"
            :visible.sync="dialogVisible"
            width="30%"
            class="rich-dialog">
            <div>
                <p class="titleName">
                    <span>标题:</span>{{ $route.query.name }}
                </p>
                <div v-html="$route.query.description" class="content"></div>
            </div>
        </el-dialog>
    </page-box>
</template>

<script lang="ts">
import { Component, Provide, Vue } from "vue-property-decorator";
import PreviewTemplate from "@/views/module-manage/src/components/preview-template/index.vue";

@Component({
    name: "DeclareFillInNotAlive",
    components: {
        PreviewTemplate
    }
})
export default class DeclareFillIn extends Vue {
    key = 0;
    dialogVisible = false;

    @Provide("dataForm")
    dataForm() {
        return this._dataForm;
    }

    get isEdit() {
        return this.$route.query.dataFormId;
    }

    get descriptionType() {
        return this.$route.query.descriptionType;
    }

    get allOnlyItem() {
        const getItem = (arr: any) => {
            let list: any[] = [];
            arr.forEach((item: any) => {
                if (item.itemType === 2) {
                    list.push(item);
                } else {
                    list = list.concat([], getItem(item.items));
                }
            });
            return list;
        };

        return getItem((this.$refs.previewTemplate as any).list);
    }

    _dataForm: any = {};
    show = false;
    // 所有填报数据,提交的
    allItemValueList: any[] = [];
    formRuleTips = ""

    created() {
        if (this.$route.query.dataFormId) {
            this.initData();
        } else {
            this.show = true;
        }
    }

    async initData() {
        const res = await this.$server["moduleManage/collection/getDetail"]({
            data: {
                formId: this.$route.query.id,
                dataFormId: this.$route.query.dataFormId
            }
        });
        if (res.data.code === 200) {
            this._dataForm = res.data.data;
            this.show = true;
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    save(type?: string) {
        const fillInTable: any =
            ((this.$refs.previewTemplate as any).$refs.PreviewForm as any).$refs
                .FillInTable || [];
        const table = fillInTable.map((item: any) => item.save());

        const groupItem: any =
            ((this.$refs.previewTemplate as any).$refs.PreviewForm as any).$refs
                .GroupItem || [];
        const groupTable: any[] = [];
        groupItem.forEach((item: any) => {
            groupTable.push(...item.save());
        });

        const allTable = groupTable.concat([], table);
        const resData = {
            info: {
                city: "武侯区",
                town: "天池镇",
                village: "洪山村",
                gis: "12312.321321.321",
                address: "四川省成都市武侯区天池镇洪山村7组74号",
                processInstId: this.$route.query.processInstanceId
            },
            children: {
                formId: this.$route.query.id,
                items: this.buildData(
                    allTable,
                    (this.$refs.previewTemplate as any).list
                )
            }
        };
        const getItem = (arr: any) => {
            let list: any[] = [];
            arr.forEach((item: any) => {
                if (item.itemType === 2) {
                    list.push(item);
                } else {
                    list = list.concat([], getItem(item.children.items));
                }
            });
            return list;
        };
        this.allItemValueList = getItem(resData.children.items);
        if (this.checkData(resData.children.items)) {
            this.$message.error(this.formRuleTips || "请完成表单带*号必填项后再保存!");
        } else {
            this.toSubmit(resData, type);
        }
    }

    // 提交
    async toSubmit(data: any, type?: string) {
        const url = this.isEdit ? "moduleManage/collection/update" : "moduleManage/collection/finIn";
        const resData = {
            dataFormId: this.isEdit || undefined,
            formId: data.children.formId,
            items: data.children.items,
            processInstId: this.$route.query.processInstanceId
        };
        const res = await this.$server[url]({
            data: this.isEdit ? resData : data
        });
        if (res.data.code === 200) {
            this.$message.success("保存成功");
            if (type === "toNext") {
                this.key++;
            } else {
                this.goBack();
            }
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 校验数据必填
    checkData(list: any[]): boolean | string {
        for (let i = 0; i < list.length; i++) {
            if (list[i].itemType === 2) {
                if (!this.checkItem(list[i])) {
                    return true;
                }
            } else if (list[i].itemType === 1) {
                if (this.checkData(list[i].children.items)) {
                    return this.checkData(list[i].children.items);
                }
            } else if (list[i].itemType === 0) {
                if (this.checkData(list[i].children.items)) {
                    return this.checkData(list[i].children.items);
                }
            }
        }
        return false;
    }

    // 展示富文本
    showRichText() {
        this.dialogVisible = true;
    }

    // 校验表单项是否为空
    checkItem(obj: any) {
        this.formRuleTips = "";
        // 非必填
        if (!obj.required) {
            if (obj.itemValue) {
                // 有值校验
                if (this.checkRule(obj)) {
                    return true;
                } else {
                    this.formRuleTips = "请填写正确的" + obj.name;
                    return false;
                }
            } else {
                // 没值通过
                return true;
            }
        }

        // 获取当前表单项内容
        const node = this.allOnlyItem.filter(
            (item: any) => item.id === obj.itemId
        );
        if (node.length) {
            const { cascadeId, cascadeOptionIds } = node[0];
            // 查找绑定的父级（单选）的表单项(带值的)
            const controlItem = this.allItemValueList.filter((item: any) => item.id === cascadeId);
            if (controlItem.length) {
                // 找到选项的id
                const optionsId = controlItem[0].options.filter((item: any) => item.name === controlItem[0].itemValue);
                if (optionsId.length) {
                    // 在绑定的值中，则是要显示，需要校验必填
                    if (cascadeOptionIds.includes(optionsId[0].id)) {
                        if (obj.itemValue) {
                            if (this.checkRule(obj)) {
                                return true;
                            } else {
                                this.formRuleTips = "请填写正确的" + obj.name;
                                return false;
                            }
                        }
                        if (obj.extData && (obj.extData.length || obj.extData.cityAddress)) {
                            return true;
                        }
                    } else {
                        obj.itemValue = "";
                        obj.extData = null;
                        return true;
                    }
                }
            }
        }

        if (obj.itemValue) {
            if (this.checkRule(obj)) {
                return true;
            } else {
                this.formRuleTips = "请填写正确的" + obj.name;
                return false;
            }
        }
        if (obj.extData && (obj.extData.length || obj.extData.cityAddress)) {
            return true;
        }
        return false;
    }

    // 校验格式 true是可以
    checkRule(item: any) {
        if (item.valueLength) {
            return item.itemValue.length === item.valueLength;
        } else {
            return true;
        }
    }

    // 组装数据
    buildData(tableList: any, dataList: any) {
        const list = dataList;
        const res: any[] = [];
        list.forEach((item: any) => {
            if (item.itemType === 0) {
                res.push({
                    ...item,
                    itemId: item.id,
                    children: item.childrenFormId
                        ? {
                              formId: item.childrenFormId,
                              items: this.buildData(tableList, item.items)
                        }
                        : undefined
                });
            } else if (item.itemType === 1) {
                const cur = tableList.filter((it: any) => it.id === item.id)[0];
                res.push({
                    ...item,
                    itemId: item.id,
                    children: item.childrenFormId
                        ? {
                              formId: item.childrenFormId,
                              items: this.buildTableData(cur.tableData)
                        }
                        : undefined
                });
            } else if (item.itemType === 2) {
                res.push({ ...item, itemId: item.id });
            }
        });
        return res;
    }

    // 组装子表数据
    buildTableData(tableData: any) {
        const res: any[] = [];
        tableData.forEach((item: any, index: any) => {
            item.forEach((it: any) => {
                res.push({
                    dataItemId: it.dataItemId,
                    itemId: it.id,
                    valueKindId: it.valueKindId,
                    itemType: it.itemType,
                    extData: it.extData,
                    itemValue: it.itemValue,
                    sort: it.sort,
                    lineNum: index + 1,
                    required: it.required
                });
            });
        });
        return res;
    }

    goBack() {
        this.$router.back();
    }
}
</script>
<style lang="scss" scoped>
::v-deep {
    .page-base-body {
        background: #edeff2 !important;
        height: calc(100% - 50px) !important;
    }
    .preview-template-container {
        height: calc(100% - 100px);
        background: #fff;
        overflow-y: auto;
    }
    .pbb__search-column.fixed-column {
        padding: 10px 18px;
        height: 90px !important;
    }
}
.fixed-column {
    .title {
        width: 100%;
        display: flex;
        flex-direction: column;
        line-height: 36px;
    }
    .name {
        font-size: 16px;
        margin-right: 20px;
    }
    .description {
        color: #c3c3c3;
        margin: 0;
        padding: 0;
        font-size: 14px;
        max-width: 640px;
        @include textEllipsis();
    }
    .btn {
        font-size: 14px;
        color: #2c82c9;
        cursor: pointer;
        padding: 0;
        margin: 0;
        &:hover {
            text-decoration: underline;
        }
    }
}

.rich-dialog {
    ::v-deep {
        .el-dialog__header {
            border-bottom: 1px solid #ccc;
        }
        .el-dialog__body {
            padding: 10px 20px;
            .titleName {
                font-size: 16px;
                padding: 0;
                margin: 0 0 10px 0;
            }
            .content {
                max-height: 600px;
                overflow-y: scroll;
            }
        }
    }
}
</style>
